/*子应用*/
const express = require('express');
const query = require('../pool');
const register = express.Router();
const sms = require('../modules/login/smscode');

// 注册获取验证码
register.get('/mobile?:phone', async(req, res) => {
  let obj = req.query;
  phone = obj.phone;
  // 查询系统是否存在手机号
  let sql = 'select 1 from cake_user where phone = ? and upwd is not null';
  let rows = await query(sql,[obj.phone])
  if(rows.length==0){
    let smscode =await sms(obj.phone);
    let rows = await query('select 1 from cake_user where phone = ?',[obj.phone]);
    // console.log(rows);
    // 判断数据库是否存了该手机号，没有就新增，有就更新
    if(rows.length==0){
      let result = await query('insert into cake_user (phone,regcode) value (?,?)',[obj.phone,smscode]);
      if(result.affectedRows==0){
        res.send({code:0,msg:'数据插入失败'})
      }else{
        res.send({code:1,msg:"验证码插入数据成功"})
      }
    }else{
      let result = await query('update cake_user set regcode = ? where phone = ?',[smscode,obj.phone]);
      if(result.length == 0){
        res.send({code:0,msg:'数据更新失败'})
      }else{
        res.send({code:1,msg:'数据更新成功'})
      }
    }
  }else{
    res.send({code:0,msg:'该手机号已被注册'})
  }
})

// 注册用户
register.post('/',async(req,res,next)=>{
  let obj = req.body;
  let sql = 'update cake_user set uname = ?,upwd = md5(?),user_icon="images/details/details_1.jpg",user_integral=50 where phone = ? and regcode = ?';
  let rows = await query(sql,[obj.uname,obj.upwd,obj.phone,obj.telCode]);
  // console.log([obj.uname,obj.upwd,obj.phone,obj.telCode],rows);
  if(rows.affectedRows==0){
    res.send({code:0,msg:'验证码不正确'})
  }else{
    res.send({code:1,msg:'注册成功'})
  }
})
//暴露
module.exports = register;
